/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.transform_t2d.var.calc;

import java.math.BigDecimal;

/**
 *  Use {@link BigDecimal} for indicate number
 * @author yura
 */
public class Opperation {

    public static final int ADD = 0;
    public static final int DIVIDE = 2;
    public static final int MINUS = 1;
    public static final int MULTIPLY = 3;
    public static final int POW = 4;

    public Number add(Number d1, Number d2) {
        if (d1 instanceof BigDecimal){
            return ((BigDecimal)d1).add((BigDecimal) d2);
        }
        return opperation(d1, d2, ADD);
    }

    public Number minus(Number d1, Number d2) {
        if (d1 instanceof BigDecimal){
            return ((BigDecimal)d1).subtract((BigDecimal) d2);
        }
        return opperation(d1, d2, MINUS);
    }

    public Number divide(Number d1, Number d2) {
        if (d1 instanceof BigDecimal){
            return ((BigDecimal)d1).divide((BigDecimal) d2);
        }
        return opperation(d1, d2, DIVIDE);
    }

    public Number multiply(Number d1, Number d2) {
        if (d1 instanceof BigDecimal){
            return ((BigDecimal)d1).multiply((BigDecimal) d2);
        }
        return opperation(d1, d2, MULTIPLY);
    }

    public Number pow(Number d1, Number d2) {
        if (d1 instanceof BigDecimal){
            return ((BigDecimal)d1).pow(d2.intValue());
        }
        return opperation(d1, d2, POW);
    }

    public Number negative(Number n1){
        if (n1 instanceof BigDecimal){
            return ((BigDecimal)n1).negate();
        }
        return 0 - n1.doubleValue();
    }

    public Number num(Number n1){
        return new BigDecimal(n1.toString());
    }

    private Number opperation(Number n1, Number n2, int opp)
            throws IllegalArgumentException {

        switch (opp) {
            case ADD:
                return n1.doubleValue() + n2.doubleValue();
            case MINUS:
                return n1.doubleValue() - n2.doubleValue();
            case DIVIDE:
                return n1.doubleValue() / n2.doubleValue();
            case MULTIPLY:
                return n1.doubleValue() * n2.doubleValue();
            case POW:
                return Math.pow(n1.doubleValue(), n2.doubleValue());
        }
        throw new IllegalArgumentException();
    }
}
